package leetcodev1.字符串;

import leetcodev1.链表.Solution;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LeetCode151 {

    //从后向前的遍历字符串即可
    public String reverseWords(String s) {
        StringBuilder ret = new StringBuilder();
        int length = s.length(), index = length - 1;
        StringBuilder tmp = new StringBuilder();
        while (index >= 0) {
            if (s.charAt(index) == ' ') {
                if (tmp.length() > 0) {
                    ret.append(tmp.reverse()).append(' ');
                    tmp.delete(0, tmp.length());//清空
                }
            } else {
                tmp.append(s.charAt(index));
            }

            index--;
        }

        if (tmp.length() > 0) {
            ret.append(tmp.reverse());
        } else {
            ret.deleteCharAt(ret.length() - 1);
        }

        return ret.toString();
    }

    //利用api完成即可
    public String reverseWords1(String s) {
        // 除去开头和末尾的空白字符
        s = s.trim();
        // 正则匹配连续的空白字符作为分隔符分割
        List<String> wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        return String.join(" ", wordList);
    }
}
